package cn.bonoon.controllers.fmm;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.servlet.http.HttpServletRequest;

import org.batatasframework.common.ParameterReader;
import org.batatasframework.monitor.LogonAccountMonitoring;
import org.batatasframework.web.RequestParameterReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.bonoon.core.plugins.LogonService;
import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.security.LogonUserRuntimeCollection;
import cn.bonoon.kernel.web.controllers.AbstractLayoutController;

@Controller
@RequestMapping("s/sys/logon")
public class AccountLogonController extends AbstractLayoutController{

//	private final static int DEFAULT_LOGON_USER_SIZE = 100;
	@Autowired(required = false)
	private LogonAccountMonitoring logonAccountMonitoring;
	
	@Autowired
	private LogonService logonService;

	@Override
	protected void onLoad(PanelEvent event) throws Exception {
		internalLoad(event.getModel().getModelMap(), event.getModel().getRequest());
		event.setVmPath("sys/logon-users");
	}

	@RequestMapping(value = "!{key}/load.do", method = POST)
	public String load(ModelMap model, HttpServletRequest request){
		try{
			internalLoad(model, request);
		}catch (Exception e) {
			log(e);
		}
		model.addAttribute("layout", "layout-empty.vm");
		return "sys/logon-users-content";
	}
	
	private LogonUserRuntimeCollection internalLoad(ModelMap model, HttpServletRequest request, ParameterReader para) throws Exception{
		LogonUserRuntimeCollection lurCollection = logonAccountMonitoring.getLogonUsers(request, para);
		model.addAttribute("users", lurCollection);
		return lurCollection;
	}

	private void internalLoad(ModelMap model, HttpServletRequest request) throws Exception{
		ParameterReader para = RequestParameterReader.valueOf(request);
		internalLoad(model, request, para);
	}
	
	@RequestMapping(value = "!{key}/out.do", method = POST)
	public String out(ModelMap model, HttpServletRequest request){
		ParameterReader para = RequestParameterReader.valueOf(request);
		try{
			
			//这里验证一下，如果密码不正确，则不允许退出其他用户的登录
			logonService.verify(getUser(), para.getString("p"));
			
			model.addAttribute("users", logonAccountMonitoring.userLogout(request, para));

		}catch (Exception ex) {
			try{
				LogonUserRuntimeCollection lurCollection = internalLoad(model, request, para);
				lurCollection.setMessage(ex.getMessage());
			}catch (Exception e) {
				log(e);
			}
		}
		model.addAttribute("layout", "layout-empty.vm");
		return "sys/logon-users-content";
	}
}
